package consumer.controller;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;

import java.util.List;

public class consumerController {

    public static void main(String[] args) throws Exception {
        broadcastConsumption(creatConsumer());
    }

    public static DefaultMQPushConsumer creatConsumer() throws Exception {
        //实例化消费者，指定组名：TopicTest
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("tttgro_ne");
        //指定nameserver地址信息
        consumer.setNamesrvAddr("localhost:9876");
        //订阅topic
        consumer.subscribe("TopicTest", "*");//tag tagA/b/c
        return consumer;
    }

    public static void clusterConsumption(DefaultMQPushConsumer consumer) throws Exception {
        //  一条消息同一个消费者组中只有一个消费者会消费到
        consumer.setMessageModel(MessageModel.CLUSTERING);//设置集群消费模式
        consumption(consumer);
    }

    public static void broadcastConsumption(DefaultMQPushConsumer consumer) throws Exception {
        consumer.setMessageModel(MessageModel.BROADCASTING);//广播消费

        // 注册回调函数，处理消息
        consumption(consumer);
    }

    public static void consumption(DefaultMQPushConsumer consumer) throws MQClientException {
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
                                                            ConsumeConcurrentlyContext context) {
                try {
                    for (MessageExt msg :
                            msgs) {
                        String topic = msg.getTopic();
                        String body = new String(msg.getBody(), "utf-8");
                        String tags = msg.getTags();
                        System.err.println("收到消息：" + "topic：" + topic + ",tags:" + tags + ",msg:" + body);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        //启动消息者
        consumer.start();
        System.out.printf("消费者启动");
//        consumer.shutdown();
    }


}
